package com.ht.web360.base.config.web;

import feign.RequestInterceptor;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Configuration
@Slf4j
public class FeignConfiguration {
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes instanceof ServletRequestAttributes sra) {
                HttpServletRequest request = sra.getRequest();
                String cookie = request.getHeader("cookie");
                requestTemplate.header("cookie", cookie);
                // StringBuilder builder = new StringBuilder();
                // Cookie[] cookies = request.getCookies();
                // for (int i = 0; i < cookies.length; i++) {
                //     Cookie cookie = cookies[i];
                //     builder.append(cookie.getName())
                //             .append('=')
                //             .append(cookie.getValue());
                //     if (i != cookies.length - 1) {
                //         builder.append(';');
                //     }
                // }
                // requestTemplate.header("cookie", builder.toString());
            }
        };
    }

    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder();
    }
}
